<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\base;

use builder\helper\H5;

/**
 * 构建器trait
 * @author cleverstone
 * @since ym2.0
 */
trait BuilderTrait
{
    /**
     * 格式化css样式
     * @param string|array $style
     */
    protected function formatStyle(&$style)
    {
        if (is_array($style)) {
            $style = H5::cssStyleFromArray($style);
        }
    }

    /**
     * 格式化css UI
     * @param array|string $class
     */
    protected function formatUiClass(&$class)
    {
        if (is_array($class)) {
            $class = implode(' ', $class);
        } else {
            $class = ltrim($class);
        }
    }

    /**
     * 格式化html属性
     * @param array|string $attribute
     */
    protected function formatHtmlAttribute(&$attribute)
    {
        if (is_array($attribute)) {
            $attribute = H5::renderTagAttributes($attribute);
        } else {
            $attribute = ' ' . ltrim($attribute);
        }
    }

    /**
     * 闭包DI
     * @param \Closure $closure
     * @param string $type
     * @return mixed
     * @throws UndefinedParamsException
     * @throws \ReflectionException
     */
    protected function closureDi($closure, $type)
    {
        $reflectionFunc = new \ReflectionFunction($closure);
        $depend = [];
        foreach($reflectionFunc->getParameters() as $value) {
            if ($value->isDefaultValueAvailable()){
                $depend[] = $value->getDefaultValue();
            } else {
                if (PHP_VERSION_ID >= 80000) {
                    $c = $value->getType();
                    $isClass = false;
                    if ($c instanceof \ReflectionNamedType) {
                        $isClass = !$c->isBuiltin();
                    }

                    $class = $isClass ? (new \ReflectionClass($c->getName())) : null;
                } else {
                    $class = $value->getClass();
                }
                if (!is_null($class)) {
                    $object = $class->newInstance();
                    if ($object instanceof $type) {
                        $depend[] = $object;
                    } else {
                        throw new UndefinedParamsException("Function parameters {$class} is not supported. ");
                    }

                    continue;
                }

                $depend[] = null;
            }
        }

        return call_user_func_array($closure, $depend);
    }
}